package main

import (
	// "log"

	"fmt"
	"io"
	"os"
	"os/exec"
	"runtime"
	"strings"
)

// 粘贴选定的单个文件
// https://github.com/mactsouk/opensource.com/blob/master/cp1.go
func Copy(src, dst string) (int64, error) {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return 0, err
	}

	if !sourceFileStat.Mode().IsRegular() {
		return 0, fmt.Errorf("%s is not a regular file", src)
	}

	source, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return 0, err
	}
	defer destination.Close()
	nBytes, err := io.Copy(destination, source)
	return nBytes, err
}

// https://blog.csdn.net/fwhezfwhez/article/details/97390199
// golang 文件夹复制，支持各种嵌套
func CopyDir(src string, dest string) error {
	src = FormatPath(src)
	dest = FormatPath(dest)
	// log.Println(src)
	// log.Println(dest)

	var cmd *exec.Cmd

	switch runtime.GOOS {
	case "windows":
		// 粘贴选定的文件或选定目录下的所有文件(非递归)，如有同名文件则覆盖
		cmd = exec.Command("xcopy", src, dest, "/I", "/y")
		// https://learn.microsoft.com/en-us/previous-versions/orphan-topics/ws.10/cc773364(v=ws.10)?redirectedfrom=MSDN
		// cmd = exec.Command("xcopy", src, dest, "/I", "/E")
	case "darwin", "linux":
		cmd = exec.Command("cp", "-R", src, dest)
	}

	e := cmd.Run()
	// outPut, e := cmd.Output()
	if e != nil {
		return e
	}
	// fmt.Println(string(outPut))
	return nil
}

func FormatPath(s string) string {
	switch runtime.GOOS {
	case "windows":
		return strings.Replace(s, "/", "\\", -1)
	case "darwin", "linux":
		return strings.Replace(s, "\\", "/", -1)
	default:
		// logger.Println("only support linux,windows,darwin, but os is " + runtime.GOOS)
		return s
	}
}

// func main() {
// 	// windows
// 	copyDir("d:/tmp", "d:/tmp2")
// 	// linux, mac
// 	copyDir("/home/tmp", "/home/tmp2")
// }
